<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="funsBtn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in studentsList" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="delInfo(item.id)">删除</button>
            <button @click="editInfo(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      studentsList: [
        { id: 99, uname: '张三', age: 18, gender: '男' },
        { id: 67, uname: '李四', age: 20, gender: '男' },
        { id: 76, uname: '王武', age: 35, gender: '男' },
      ],
      uname: '',
      age: '',
      gender: '',
      editIndex: '',
    }
  },
  methods: {
    //添加 编辑模块
    funsBtn() {
      if (this.uname && this.age && this.gender) {
        const obj = {
          id: this.studentsList.length + 1,
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        }
        // console.log(obj)
        if (this.editIndex || this.editIndex === 0) {
          this.studentsList.splice(this.editIndex, 1, obj)
          this.uname = ''
          this.age = ''
          this.gender = ''
        } else {
          this.studentsList.push(obj)
          this.uname = ''
          this.age = ''
          this.gender = ''
        }
      } else {
        alert('请输入必填项喔～')
      }
    },
    //编辑功能
    editInfo(index) {
      const newData = this.studentsList[index]
      this.uname = newData.uname
      this.age = newData.age
      this.gender = newData.gender
      this.editIndex = index
      // console.log(this.editIndex)
    },
    //删除功能
    delInfo(id) {
      this.studentsList = this.studentsList.filter((item) => item.id !== id)
    },
  },
}
</script>
